package com.mrslu.signkk.service.impl;

import com.alibaba.fastjson2.JSON;
import com.mrslu.signkk.dao.UserInfoDao;
import com.mrslu.signkk.interceptor.TokenCensor;
import com.mrslu.signkk.management.WeChatLoginResult;
import com.mrslu.signkk.management.WeChatUserManagement;
import com.mrslu.signkk.pojo.User;
import com.mrslu.signkk.pojo.identity.UserRoleEnum;
import com.mrslu.signkk.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Value("${default-org}")
    private Integer defaultOrgId;

    private final UserInfoDao userDao;

    private final WeChatUserManagement weChatUserManagement;

    private final TokenCensor tokenCensor;

    private final RedisTemplate<String, String> redisTemplate;

    @Autowired
    public UserServiceImpl(UserInfoDao userDao, WeChatUserManagement weChatUserManagement, TokenCensor tokenCensor, RedisTemplate<String, String> redisTemplate) {
        this.userDao = userDao;
        this.weChatUserManagement = weChatUserManagement;
        this.tokenCensor = tokenCensor;
        this.redisTemplate = redisTemplate;
    }


    /**
     * 用户登录与注册；
     * - 存在用户信息则登录，数据库中如果没有该用户的openId则先完成基础的注册
     *
     * @param code 登录code
     * @return token
     */
    @Override
    public String userLogin(String code) {
        // 调用微信小程序官方登录接口获取OpenId和SessionKey
        WeChatLoginResult loginResult = weChatUserManagement.requestLogin(code);
        // 根据用户的openId尝试获取用户实体信息
        User userEnt = userDao.getUserBaseInfoByOpenId(loginResult.getOpenId());
        // 如果无法拿到用户信息，说明用户是第一次登录则开始注册过程
        if (userEnt == null) {
            //注册一个新用户，仅包含最基本的信息（openId，默认的用户角色）
            userDao.saveUserBaseInfo(defaultOrgId, UserRoleEnum.PARTNER, loginResult.getOpenId());
            userEnt = userDao.getUserBaseInfoByOpenId(loginResult.getOpenId());
        }
        // 签发token，返回给用户
        return tokenCensor.tokenIssue(userEnt.getId(), userEnt.getUserRole(), userEnt.getOrgId(), loginResult.getSessionKey());
    }

    /**
     * 更新用户基本信息
     *
     * @param user 用户基本信息
     * @return 新用户信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public User updateUserDetail(User user) {
        User.checkUserParam(user);
        log.info("更新用户信息参数：{}", JSON.toJSONString(user));
        userDao.updateUserInfo(user.getId(), user.getOrgId(), user.getUserName(), user.getPhoneNumber());
        return userDao.getUserDetailInfo(user.getOrgId(), user.getId());
    }

    /**
     * 获取用户基本信息
     *
     * @param orgId  机构ID
     * @param userId 用户ID
     * @return 用户基本信息
     */
    @Override
    public User getUserDetail(Integer orgId, Integer userId) {
        return userDao.getUserDetailInfo(orgId, userId);
    }

}
